const fs = require("fs")

fs.readFile("./images/1.txt", "utf8", (err, dataStr) => {
    if (err) {
        console.log(err)
    } else {
        console.log(dataStr)
    }
})

fs.readFile("./images/yx_back.png", (err, dataStr) => {
    if (err) {
        console.log(err)
    } else {
        console.log(dataStr)
    }
})


fs.open("./images/1.txt", "r", (err, fd) => {
    if (err) throw err
    console.log("打开文件...")
    let buffer = Buffer.alloc(1024)
    fs.read(fd, buffer, 0, buffer.length, 0, (err, bytesRead, buffer) => {
        if (err) throw err
        console.log(`读取字节${bytesRead}`)
        console.log(buffer.subarray(0, bytesRead).toString())
        fs.close(fd, err => {
            if (err) throw err

        })
    })
})


// const fsPromises = fs.promises
//     (async file => {
//         let filehandle
//         try {
//             filehandle = await fsPromises.open(file)
//             console.log(`已打开${file}文件`)
//             let buffer = Buffer.alloc(1024)
//             let res = await filehandle.read(buffer, 0, buffer.length, 0)
//             console.log(`读取字节${res.bytesRead}\n`)
//             console.log(`${res.buffer.toString()}`)
//         } catch (error) {
//             console.error(error)
//         } finally {
//             if (filehandle) {
//                 await filehandle.close()
//             }
//         }
//     })("./images/1.txt")

const readFile = async (file) => {
    let filehandle
    try {
        filehandle = await fs.promises.open(file)
        console.log(`已打开${file}文件`)
        let buffer = Buffer.alloc(1024)
        let res = await filehandle.read(buffer, 0, buffer.length, 0)
        console.log(`读取字节${res.bytesRead}\n`)
        console.log(`${res.buffer.toString()}`)
    } catch (error) {
        console.error(error)
    } finally {
        if (filehandle) {
            await filehandle.close()
        }
    }
}

readFile("./images/1.txt")

let data = "Hello,Node.js.欢迎使用"
fs.writeFile("./images/1.txt", data, err => {
    if (err) {
        console.log(err)
    } else {
        console.log("写入成功")
    }
})